local itemBar = require 'View/CommonUI/ComResBar'

--- @class UIDebrisInfo
local UIDebrisInfo = UIBase.New(PanelResNames.UIDebrisInfo)
local M = UIDebrisInfo

local m_chip_info = nil
local m_skill_ls = nil
local m_view_type = nil
local m_attr

local mListSubSkillHeight = 0

function UIDebrisInfo.Init(data, viewType)
    m_chip_info = data
    m_view_type = viewType

    UIBase.Init(UIDebrisInfo)
end

function UIDebrisInfo:OnCreate()
    self:RegisterOnClick(self:GetChild("bgclose"), self.OnClick_close)
    self:RegisterOnClick(self:GetChild("btnLevelUp"), self.OnClick_levelup)
    self:RegisterOnClick(self:GetChild("btnBreak"), self.OnClick_broken)
    self:RegisterOnClick(self:GetChild("btnBaptism"), self.OnClick_baptism)
    self:RegisterOnClick(self:GetChild("btnChange"), self.OnClick_change)
    self:RegisterOnClick(self:GetChild("btnLock"), self.OnClick_lock)
    self:RegisterOnClick(self:GetChild("btnRemove"), self.OnClick_remove)
    
    self.img_type   = self:GetChild("type")
    self.txt_type   = self:GetChild("textType")
    self.item       = self:GetChild("item")
    self.name       = self:GetChild("name")
    self.power      = self:GetChild("power")
    -- self.mainSkill  = self:GetChild("mainSkill/textSkillType")
    -- self.listSubSkill = self:GetChild("listSubSkill")
    self.btnLock    = self:GetChild("btnLock")
    self.ctr_lock   = self.btnLock:GetController("button")
    self.ctr_type   = self:GetController("type")
    self.btn_level  = self:GetChild("btnLevelUp")
    self.btn_change = self:GetChild("btnChange")
    self.ctr_atrr   = self:GetController("attr")
    -- self.listAttr   = self:GetChild("attrlist")

    local infolist = self:GetChild("debrisInfo")
    local panel = infolist:GetChildAt(0)
    self.listSubSkill = panel:GetChild("listSubSkill")
    self.listAttr     = panel:GetChild("attrlist")
    self.mainSkill    = panel:GetChild("mainSkill"):GetChild("textSkillType")
    self.ctrlSubSkill = panel:GetController("subSkill")

    -- 突破和炼化消耗
    -- self.brokenCost  = decodeJsonStrToTabel(dataTable.getGlobalString(631))
    -- self.baptismCost = decodeJsonStrToTabel(dataTable.getGlobalString(632))
    -- 突破消耗材料
    -- self.costItem = self:CreateComponent(itemBar, self:GetChild("currency"))
    
    -- 突破按钮
    self.btnBroken = self:GetChild("btnBreak")
    -- 突破tip
    self:GetChild("breakTips").text = getLanguage("DebrisText17")

    self.ctr_atrr.selectedIndex = 1

    -- 页面类型
    if m_view_type == EnumConst.DebrisInfoType.Bag then
        self.ctr_type.selectedIndex = 0
    elseif m_view_type == EnumConst.DebrisInfoType.View then
        self.ctr_type.selectedIndex = 2
    else
        -- self.ctr_type.selectedIndex = 1
        self.ctr_type.selectedIndex = self:checkViewType()
    end

    self.listSubSkill.itemRenderer = self.BindSkill

    self.listAttr.itemRenderer = UIDebrisInfo.AttrRender
end

function UIDebrisInfo:OnEnable()
    ListenEvent(Config.EventType.Fragment_Unwear, self.Unwear, self)
    UIRedDots.addViewListen(PanelResNames.UIDebrisInfo, PanelNames.UIDebrisInfo.."btn_levelup", UIDebrisInfo.btn_level, Config.RedDotsType.debrisUpgrade, m_chip_info);
    UIRedDots.addViewListen(PanelResNames.UIDebrisInfo, PanelNames.UIDebrisInfo.."btn_change", UIDebrisInfo.btn_change, Config.RedDotsType.debrisChange, m_chip_info);
    UIRedDots.addViewListen(PanelResNames.UIDebrisInfo, PanelNames.UIDebrisInfo.."btnBroken", UIDebrisInfo.btnBroken, Config.RedDotsType.debrisBroken, m_chip_info);

    -- ListenEvent(Config.EventType.DebrisUpdate, self.RefreshItem, self)
    if m_view_type == EnumConst.DebrisInfoType.Bag then
        self:RefreshItem()
    elseif m_view_type == EnumConst.DebrisInfoType.View then
        self:RefreshViewItem()
    else
        self:RefreshItem()
    end

    -- self:refreshBrokenCostUI()
end

--- 获取页面类型 
--- @return number 
function UIDebrisInfo:checkViewType()
    if m_chip_info.quality == EnumConst.DebrisQuality.Immortal then
        return 3
    elseif m_chip_info.quality == EnumConst.DebrisQuality.Dark then
        return 4
    else
        return 1
    end
end

function UIDebrisInfo:Unwear()
    closeUI(PanelResNames.UIDebrisInfo)
end

function UIDebrisInfo:OnDisable()
    CloseEvent(Config.EventType.Fragment_Unwear, self.Unwear, self)
    UIRedDots.removeViewEvent(PanelResNames.UIDebrisInfo)
end

function UIDebrisInfo.AttrRender(index, obj)
    local txt_name = obj:GetChild("name")
    local txt_value = obj:GetChild("value")
    local txt_refine = obj:GetChild("refine")

    local attr = m_attr[index + 1]
    local at = G.dataTable["t_attributelibrary"][tostring(attr.now[1])]
    if at then
        local basic = attr.basic and attr.basic[2] or 0
        txt_name.text = at.f_AttributeName
        local tempNum = 1
        if UIDebrisInfo.ctr_type.selectedIndex==1 then
            if logicMgr.HeroPotentialMgr.IsAtkHpDef(attr.now[1]) then
                tempNum = logicMgr.HeroPotentialMgr.DebrisCrease()
            end
        end
        txt_refine.text = Mathf.Round(basic * tempNum)
        local delta = attr.now[2] - basic
        if delta == 0 then
            txt_value.text = ""
        else
            local type = at.f_AttributeType
            if type == 2 then
                txt_value.text =  "+" .. delta * 0.01 .. "%"
            else
                txt_value.text =  "+" .. delta
            end
        end
    end
end

--道具预览
function UIDebrisInfo:RefreshViewItem()
    self.name.text = m_chip_info.name
    -- self.power.text = m_chip_info.addPower
    self.mainSkill.text = logicMgr.StrangeFragmentManager.GetMainDesc(m_chip_info.itemModelId, 1)
    
    local item = CtrlManager.GetCtrl(PanelNames.Item);
    if item then
        item.initData(self.item, m_chip_info, 1)
    end

    local config = G.dataTable["t_debris"][tostring(m_chip_info.itemModelId)]
    self.img_type.url =  EnumConst.Path_DebrisTypeIcon["type_" .. config.f_DebrisType]
    self.txt_type.text = getLanguage("DebrisType" .. config.f_DebrisType)

    local config = G.dataTable["t_debris"][tostring(m_chip_info.itemModelId)]
    if config then
        local power = dataTable.getDataTableByStringId("t_debrismajorskill",config.f_SkillId + 1,"f_DebrisLevelPower")
        self.power.text = getNumString(power)

        local als = StrangeFragmentManager.GetChipAttr(m_chip_info.itemModelId, 1)
        local bls = StrangeFragmentManager.GetChipAttr(m_chip_info.itemModelId, 1)
        m_attr = {}
        if als then
            for k,v in pairs(als) do
                table.insert(m_attr, {basic = bls[k], now = v})
            end
        end
        self.listAttr.numItems = #m_attr
    end
end

--背包预览和操作
function UIDebrisInfo:RefreshItem()
    StrangeFragmentManager.SetItemData(self.item, m_chip_info, true)

    self.name.text = m_chip_info.colorname
    local tempNum = 1
    --[[if self.ctr_type.selectedIndex==1 then
        tempNum = logicMgr.HeroPotentialMgr.DebrisCrease()
    end--]]
    self.power.text = getNumString(Mathf.Round(m_chip_info.addPower*tempNum))
    self.mainSkill.text = m_chip_info.GetMainSkillDes()
    self.ctrlSubSkill.selectedIndex = 0

    local need = self:GetUpgradeNeedExp(m_chip_info)
    if need == 0 then
        -- self.btn_level.displayObject.gameObject:SetActive(false)
        self.btn_level.grayed = true
    else
        -- self.btn_level.displayObject.gameObject:SetActive(true)
        self.btn_level.grayed = false
    end

    m_skill_ls = m_chip_info.subSkills
    if m_skill_ls and #m_skill_ls > 0 then
        mListSubSkillHeight = 0
        self.listSubSkill.numItems = #m_skill_ls
        self.ctrlSubSkill.selectedIndex = 1
    end

    self.img_type.url =  EnumConst.Path_DebrisTypeIcon["type_" .. m_chip_info.debrisType]
    self.txt_type.text = getLanguage("DebrisType" .. m_chip_info.debrisType)
    
    -- self.ctr_lock.selectedIndex = m_chip_info.lock
    self.btnLock.selected = m_chip_info.lock == 1

    local als = m_chip_info.GetAttr()
    local bls = StrangeFragmentManager.GetChipAttr(m_chip_info.itemModelId, 1)
    m_attr = {}
    if als then
        for k,v in pairs(als) do
            table.insert(m_attr, {basic = bls[k], now = v})
        end
    end
    
    self.listAttr.numItems = #m_attr
end

-- 魂石突破消耗
function UIDebrisInfo:refreshBrokenCostUI()
    local costId, costNum = self.brokenCost[1], self.brokenCost[2]
    local currNum = logicMgr.ItemManager.getItemCountbyModelId(costId)
    local txtNum  = self.btnBroken:GetChild("num")
    local imgIcon = self.btnBroken:GetChild("Image")
    local costNumStr = tostring(costNum)
    if currNum < costNum then
        costNumStr = string.TextColor(costNumStr, "#FF0000");
    end

    txtNum.text = costNumStr
    imgIcon.url = EnumConst.AtlasPath.ItemAtlas .. logicMgr.ItemManager.GetItemIcon(costId)
    self.costItem:SetData(costId, costNum)
end

function UIDebrisInfo.BindSkill(index, obj)
    -- local skill = m_skill_ls[index + 1]
    -- obj:GetChild("textSkillType").text = getLanguage(skill.f_Desc)

    -- local skill = m_skill_ls[index + 1]
    -- local txt = obj:GetChild("textSkillType")
    -- txt.text = m_chip_info.GetSubSkillDes(skill.skillId)

    local txtDesc = obj:GetChild("textSkillType")
    local skillData = m_skill_ls[index + 1]
    local id, value = skillData.skillId, skillData.val
    local cfg = dataTable.getDataTableByStringId("t_debrisminorskill", tostring(id))
    txtDesc.text = cfg and string.format(getLanguage(cfg.f_text), value * cfg.f_muti * 0.0001) or ""

    mListSubSkillHeight = mListSubSkillHeight + txtDesc.height + 10
    if index == #m_skill_ls - 1 then
        UIDebrisInfo:adjustListSubSkill()
    end
end

function UIDebrisInfo:adjustListSubSkill()
    self.listSubSkill.height = mListSubSkillHeight
end

function UIDebrisInfo:OnClick_close()
    closeUI(PanelResNames.UIDebrisInfo)
end

function UIDebrisInfo:OnClick_levelup()
    local need = self:GetUpgradeNeedExp(m_chip_info)
    if need == 0 then
        UISysTips.AddMsg(getLanguage("DebrisText24"))
        return
    end

    showUI(PanelNames.UIDebrisLevelUp, m_chip_info)

    UIDebrisInfo:OnClick_close()
end

-- 突破
function UIDebrisInfo:OnClick_broken()
    -- local costId, costNum = self.brokenCost[1], self.brokenCost[2]
    -- local currNum  = logicMgr.ItemManager.getItemCountbyModelId(costId)
    -- local itemName = logicMgr.ItemManager.GetItemName(costId)
    -- if currNum < costNum then
    --     UISysTips.AddMsg(string.format(getLanguage("Character_Tips19"), itemName))
    --     return
    -- end

    if m_chip_info.quality == EnumConst.DebrisQuality.Dark then
        UISysTips.AddMsg(getLanguage("DebrisText22"))
        return
    end

    showUI(PanelNames.UIDebrisBaptism, EnumConst.DebrisViewType.Broken, m_chip_info.itemId)
    UIDebrisInfo:OnClick_close()
end

-- 炼化
function UIDebrisInfo:OnClick_baptism()
    if m_chip_info.quality ~= EnumConst.DebrisQuality.Dark then
        UISysTips.AddMsg(getLanguage("DebrisText21"))
        return
    end

    showUI(PanelNames.UIDebrisBaptism, EnumConst.DebrisViewType.Baptize, m_chip_info.itemId)
    UIDebrisInfo:OnClick_close()
end

function UIDebrisInfo:OnClick_lock()
    local lock = m_chip_info.lock == 1 and 0 or 1
    weaponHandler.ReqLockDebris(m_chip_info.partnerId, m_chip_info.itemId, lock)
end

function UIDebrisInfo:OnClick_change()
    showUI(PanelNames.UIDebrisList, {heroId = m_chip_info.partnerId, gemInfo = m_chip_info})
    closeUI(PanelResNames.UIDebrisInfo)
end

function UIDebrisInfo:OnClick_remove()
    if m_chip_info then
        weaponHandler.ReqFragmentDemount(m_chip_info.partnerId, tostring(m_chip_info.itemId))--卸下
    end
end

function UIDebrisInfo:GetUpgradeNeedExp(chip)
    local key = tonumber(chip.f_SkillId) + chip.level
    local cur_skill = dataTable.getDataTableByStringId("t_debrismajorskill",key)
    local next_skill = dataTable.getDataTableByStringId("t_debrismajorskill",key + 1)
    if next_skill then
        return next_skill.f_TotalExp
    end
   
    return 0
end

return UIDebrisInfo